SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SaveQuestionnaire]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SaveQuestionnaire]
GO

/***************************************************************************
* Name:			SaveQuestionnaire
* Purpose:		Insert/Update a questionnaire
*
* PARAMETERS
* Name			Description					
* -------------		-----------------------------------------------------------
* @id			unique id (0 for new records to be inserted)
* @name			name for the questionnaire (unique)
* @type			type of the questionnaire ex: Process, Review Sheet etc
* @category		questionnaire category ex: drugs, devices etc
* @categorySequenceNo	the order in which the questionnaires would be displayed within a category
* @description		information that describes the questionnaire
* @allowMultiple	indicates whether or not the questionnaire can have multiple questionnaire answers
* @moduleType		The BitValue of the module to which the questionnaire is tied.
***************************************************************************/
CREATE PROCEDURE [dbo].[SaveQuestionnaire] (

@id 		INTEGER,
@name		varchar(50),
@type		varchar(50),
@category	varchar(50),
@categorySequenceNo INTEGER,
@description	varchar(250),
@allowMultiple	Bit,
@moduleType INTEGER = null

)

AS

BEGIN
	IF @id = 0
	BEGIN

		DECLARE @questionnaireId INT

		INSERT INTO Questionnaire ( [Name],
					    Type,
					    Category,
					    CategorySequenceNo,
				            [Description],
					    AllowMultiple,
					    ModuleType )
			VALUES
					    ( @name,
					      @type,
					      @category,
					      @categorySequenceNo,
					      @description,
					      @allowMultiple,
					      @moduleType )
		
		IF @@ERROR <> 0 GOTO ERROR_HANDLER
		
		SELECT @questionnaireId = IDENT_CURRENT('Questionnaire')

		SELECT @questionnaireId
		RETURN 
	END
	ELSE
	BEGIN
		
		UPDATE Questionnaire
		SET
		[Name]		 = @name,
		Type		 = @type,
		Category	 = @category,
		CategorySequenceNo = @categorySequenceNo,
		[Description]	 = @description,
		AllowMultiple    = @allowMultiple,
		ModuleType	 = @moduleType
		WHERE [Id] = @id
		
		IF @@ERROR <> 0 GOTO ERROR_HANDLER

		SELECT @id	
		RETURN
		
	END

	ERROR_HANDLER:
		IF @@ERROR <> 0 
		BEGIN
			RAISERROR('Unable to Save Questionnaire', 16, 1)
			RETURN
		END
END

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

